package cn.lj.org.service.impl;

import cn.lj.base.Exception.BusinessException;
import cn.lj.base.service.impl.BaseServiceImpl;
import cn.lj.org.domain.Employee;
import cn.lj.org.domain.Shop;
import cn.lj.org.mapper.EmployeeMapper;
import cn.lj.org.mapper.ShopMapper;
import cn.lj.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)/*添加事务*/
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    @Transactional
    public void settledIn(Shop shop)  {
        /*判断密码与确认密码是否一致
        * 如果不一致就结束方法
        * */
        if(!shop.getAdmin().getPassword().equals(shop.getAdmin().getComfirmPassword())){
            return;
        }
        /*根据username,email和phone三者任意一个查询若存在都表示已经注册如果存在数据就返回一个信息：用户已经注册，清登录*/
        Employee admin = shop.getAdmin();
        Employee employee = employeeMapper.findByUsername(admin);
        if(employee != null){
            throw new BusinessException("温馨提示：用户已被注册，请登录");
        }
        /*保存到员工表employee表生成一个【主键】返回*/
        employeeMapper.save(admin);
        /*设置shop中的admin字段，此时员工表的主键Id已经返回*/
        shop.setAdmin(admin);
        /*添加shop表,返回一个组件*/
        shopMapper.save(shop);
        System.out.println(admin);
        /*设置Employee表的shop_id*/
        admin.setShop_id(shop.getId());
        /*更新Employee的shop_id，建议另外写一个方法*/
        employeeMapper.updateShop_id(admin);
    }

    @Override/*通过，修改状态值发送邮件*/
    public void updateState(Long id) {
        /*修改状态值为待激活*/
        shopMapper.updateState(id);
        /*为用户发送激活短信*/
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            /*设置发件人信息*/
            helper.setFrom("1654052648@qq.com");
            /*设置信息主题*/
            helper.setSubject("您的审核已经通过，清点击下方链接进行激活");
            /*设置信息内容*/
            helper.setText("11",true);
            /*设置收件人信息*/
            helper.setTo("1213639179@qq.com");
            /*发送邮件*/
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}
